package com.sec.etech.ism.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.ism.mapper.IsmTaskMapper;
import com.sec.etech.ism.model.IsmTask;
import com.sec.etech.sys.util.ContextUtil;
import org.openbpm.base.core.id.IdUtil;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IsmTaskService extends ServiceImpl<IsmTaskMapper, IsmTask> {

    /**
     * 检查接口返回是否成功，如果失败保存task表
     * sysCode 系统编码
     * serviceCode 应用编码
     * serviceCode 方法名称
     * businessCode 业务代码
     * businessParams 业务参数json
     * resultObj 返回参数object
     * @param object 入参
     * @return
     */
    public Long checkAndSave(JSONObject object) {
        String sysCode = object.getString("sysCode");
        String serviceCode = object.getString("serviceCode");
        String methodName = object.getString("methodName");
        String businessCode = object.getString("businessCode");
        String businessParams = object.getString("businessParams");
        JSONObject resultObj = object.getJSONObject("resultObj");
        String remark = object.getString("remark");
        Long taskId = null;

        if("SAP".equalsIgnoreCase(sysCode)) {
            taskId = this.checkSAPAndSave(sysCode, serviceCode, methodName, businessCode, businessParams, remark, resultObj);
        }else {
            taskId = this.checkAndSave(sysCode, serviceCode, methodName, businessCode, businessParams, remark, resultObj);
        }
        if(taskId==null) {//成功
            this.deleteTaskByParams(sysCode, serviceCode, methodName, businessCode, businessParams);
        }
        return taskId;
    }
    //检查sap接口返回状态
    private Long checkSAPAndSave(String sysCode, String serviceCode, String methodName, String businessCode, String businessParams, String remark, JSONObject resultObj) {
        JSONObject dataObj = resultObj!=null ? resultObj.getJSONObject("data") : null;
        if(resultObj==null || !resultObj.getBoolean("success")) {
            Long taskId = this.saveOrUpdateTask(sysCode, serviceCode, methodName, businessCode, businessParams, remark);
            return taskId;
        }else if(dataObj!=null && StringUtil.isNotEmpty(dataObj.getString("RETURN"))) {
            JSONObject returnObj = dataObj.getJSONObject("RETURN");
            if("E".equals(returnObj.getString("TYPE")) || "A".equals(returnObj.getString("TYPE"))) {
                Long taskId = this.saveOrUpdateTask(sysCode, serviceCode, methodName, businessCode, businessParams, remark);
                return taskId;
            }
        }else if(dataObj!=null && StringUtil.isNotEmpty(dataObj.getString("ITAB_RETURN"))) {
            List<JSONObject> resultList = (List<JSONObject>) dataObj.get("ITAB_RETURN");
            return this.saveTaskCheckReturns(resultList, sysCode, serviceCode, methodName, businessCode, businessParams, remark);
        }else if(dataObj!=null && StringUtil.isNotEmpty(dataObj.getString("RET"))) {
            JSONObject returnObj = dataObj.getJSONObject("RET");
            if("E".equals(returnObj.getString("TYPE")) || "A".equals(returnObj.getString("TYPE"))) {
                Long taskId = this.saveOrUpdateTask(sysCode, serviceCode, methodName, businessCode, businessParams, remark);
                return taskId;
            }
        }else if(dataObj!=null && StringUtil.isNotEmpty(dataObj.getString("RETURNS"))) {
            List<JSONObject> resultList = (List<JSONObject>) dataObj.get("RETURNS");
            return this.saveTaskCheckReturns(resultList, sysCode, serviceCode, methodName, businessCode, businessParams, remark);
        }/*else if(dataObj!=null && StringUtil.isNotEmpty(dataObj.getString("O_RETURN"))) {
            JSONObject returnObj = dataObj.getJSONObject("O_RETURN");
            if(!"S".equals(returnObj.getString("TYPE"))) {
                Long taskId = this.saveOrUpdateTask(defId, appName, businessCode, params.getJSONObject("input_params").getString("sap_params"),
                        3,null, remark);
                return taskId;
            }
        }*/
        return null;
    }
    //检查返回结果，保存错误日志
    private Long saveTaskCheckReturns(List<JSONObject> resultList, String sysCode, String serviceCode,
                                      String methodName, String businessCode, String businessParams, String remark){
        Long taskId = null;
        if(resultList!=null && resultList.size()>0) {
            boolean flag = false;
            for(JSONObject obj:resultList){//检查是否有失败的信息
                if("E".equals(obj.getString("TYPE")) || "A".equals(obj.getString("TYPE"))) {
                    flag = true;
                    break;
                }
            }
            if(flag) {
                taskId = this.saveOrUpdateTask(sysCode, serviceCode, methodName, businessCode, businessParams, remark);
            }
        }
        return taskId;
    }

    //检查通用接口返回状态
    private Long checkAndSave(String sysCode, String serviceCode, String appName, String businessCode,
                                 String businessParams, String remark, JSONObject resultObj) {
        if(resultObj.containsKey("isOk") && !resultObj.getBoolean("isOk")){
            Long taskId = this.saveOrUpdateTask(sysCode, serviceCode, appName, businessCode, businessParams, remark);
            return taskId;
        }
        return null;
    }
    /**
     * 保存任务信息
     * @param sysCode
     * @param serviceCode
     * @param methodName
     * @param businessCode
     * @param businessParams
     * @param remark
     * @return
     */
    public Long saveTask(String sysCode, String serviceCode, String methodName, String businessCode, String businessParams, String remark) {
        IsmTask ismTask = new IsmTask();
        ismTask.setId(IdUtil.getUId());
        ismTask.setSysCode(sysCode);
        ismTask.setServiceCode(serviceCode);
        ismTask.setBusinessCode(businessCode);
        //ismTask.setPlanTime(planTime);
        ismTask.setMethodName(methodName);
        ismTask.setBusinessParams(businessParams);
        ismTask.setRemark(remark);
        ismTask.setCreatedTime(new Date());
        if(ContextUtil.getCurrentUserId()!=null) {
            ismTask.setCreatedBy(ContextUtil.getCurrentUserId());
        }
        baseMapper.insert(ismTask);
        return ismTask.getId();
    }
    /**
     * 更新任务信息
     * @param id
     * @param businessCode
     * @param businessParams
     * @param remark
     * @return
     */
    public int updateTask(Long id, String businessCode, String businessParams, String remark) {
        IsmTask ismTask = new IsmTask();
        ismTask.setId(id);
        ismTask.setBusinessCode(businessCode);
        ismTask.setBusinessParams(businessParams);
        //ismTask.setPlanTime(planTime);
        ismTask.setRemark(remark);
        return baseMapper.updateById(ismTask);
    }

    /**
     * 保存或者更新任务信息
     * @param sysCode
     * @param serviceCode
     * @param methodName
     * @param businessParams
     * @return
     */
    public Long saveOrUpdateTask(String sysCode, String serviceCode, String methodName, String businessParams) {
        return this.saveOrUpdateTask(sysCode, serviceCode, methodName, null, businessParams, null);
    }
    /**
     * 保存或者更新任务信息
     * @param sysCode
     * @param serviceCode
     * @param methodName
     * @param businessCode
     * @param businessParams
     * @param remark
     * @return
     */
    public Long saveOrUpdateTask(String sysCode, String serviceCode, String methodName, String businessCode, String businessParams, String remark) {
        IsmTask ismTask = null;
        if(StringUtil.isNotEmpty(businessCode)){
            ismTask = baseMapper.selectOne(Wrappers.<IsmTask>lambdaQuery()
                    .eq(IsmTask::getSysCode, sysCode)
                    .eq(IsmTask::getServiceCode, serviceCode)
                    .eq(IsmTask::getMethodName, methodName)
                    .eq(IsmTask::getBusinessCode, businessCode));
        }else {
            ismTask = baseMapper.selectOne(Wrappers.<IsmTask>lambdaQuery()
                    .eq(IsmTask::getSysCode, sysCode)
                    .eq(IsmTask::getServiceCode, serviceCode)
                    .eq(IsmTask::getMethodName, methodName)
                    .eq(IsmTask::getBusinessParams, businessParams));
        }
        if(ismTask!=null) {
            this.updateTask(ismTask.getId(), businessCode, businessParams, remark);
            return ismTask.getId();
        }else {
            Long taskId = this.saveTask(sysCode, serviceCode, methodName, businessCode, businessParams, remark);
            return taskId;
        }
    }

    /**
     * 根据条件删除任务
     * @param sysCode
     * @param serviceCode
     * @param methodName
     * @param businessCode
     * @param businessParams
     * @return
     */
    public int deleteTaskByParams(String sysCode, String serviceCode, String methodName, String businessCode, String businessParams){
        if(StringUtil.isNotEmpty(businessCode)){
            return baseMapper.delete(Wrappers.<IsmTask>lambdaQuery()
                    .eq(IsmTask::getSysCode, sysCode)
                    .eq(IsmTask::getServiceCode, serviceCode)
                    .eq(IsmTask::getMethodName, methodName)
                    .eq(IsmTask::getBusinessCode, businessCode));
        }else {
            return baseMapper.delete(Wrappers.<IsmTask>lambdaQuery()
                    .eq(IsmTask::getSysCode, sysCode)
                    .eq(IsmTask::getServiceCode, serviceCode)
                    .eq(IsmTask::getMethodName, methodName)
                    .eq(IsmTask::getBusinessParams, businessParams));
        }
    }
}
